<!DOCTYPE html>
<html lang="zh-cn">

	<head>
		<meta charset="UTF-8">
		<title class="title">[文件管理器]</title>
		<meta name="viewport"
			content="width=device-width,initial-scale=1,minimum-scale=1,maximum-scale=1,user-scalable=no" />
		<style type="text/css">
			.content {
				background: transparent;
			}

			.btn {
				position: relative;
				top: 0;
				left: 0;
				bottom: 0;
				right: 0;
			}

			.file {
				position: fixed;
				z-index: 93;
				left: 0;
				right: 0;
				top: 0;
				bottom: 0;
				width: 100%;
				/* 安卓端动态设置opacity未生效时若要显示设置成1 */
				opacity: 0;
			}
		</style>
	</head>

	<body>

		<div id="content" class="content">
			<div id="btn" class="btn">
				<input v-if="compatibleFile" :multiple="multiple" @change="onChange" @click="onClick" :accept="accept"
					ref="file" class="file" type="file" :style="[{opacity: debug ? 1 : 0}]" />
				<div v-else @click="onClick" class="file" :style="[{opacity: debug ? 1 : 0}]"></div>
			</div>
		</div>

		<script type="text/javascript" src="js/vue.min.js"></script>
		<script type="text/javascript" src="js/permission.js"></script>
		<script type="text/javascript">
			let _this;
			var vm = new Vue({
				el: '#content',
				data: {
					accept: '',
					multiple: true,
					isIos: false,
					compatibleFile: false,
					dom: null,
					Toast: {},
					debug: false
				},
				mounted() {
					this.debug && console.log('加载webview');
					_this = this;
					this.files = new Map();
					document.addEventListener('plusready', (e) => {
						let {
							debug,
							instantly,
							prohibited,
							parent,
							isVUE3
						} = plus.webview.currentWebview();
						this.isIos = (plus.os.name == "iOS");
						this.debug = debug;
						this.instantly = instantly;
						this.prohibited = prohibited;


						let module;
						if (isVUE3 === 'YES') {
							module = parent
						} else {
							module = parent.replace(/^\.\/(.*)\.\w+$/, '$1')
						}
						if (!module.includes(atob('bHNqLQ=='))) {
							return;
						}
						if (this.prohibited.multiple === 'false') {
							this.prohibited.multiple = false;
						}
						if (this.prohibited.isPermissionInToast === 'false') {
							this.prohibited.isPermissionInToast = false;
						}
						if (this.prohibited.isPermissionInModal === 'false') {
							this.prohibited.isPermissionInModal = false;
						}
						if (this.prohibited.toBase === 'false') {
							this.prohibited.toBase = false;
						}
						
						this.accept = prohibited.accept;
						this.multiple = this.prohibited.multiple;
						location.href = 'callback?retype=updateOption';
						if (!this.isIos && this.prohibited.permission.android.length) {
							try {
								if (this.debug) {
									document.querySelector('.file').style.opacity = 1;
									document.querySelector('.file').style.background = '#000';
								}
								this.dom = document.createElement('input');
								this.dom.type = 'file';
								this.dom.value = '';
								this.dom.accept = this.accept;
								this.dom.multiple = this.multiple;
								this.dom.onchange = event => {
									this.onChange(event)
								};
							} catch (e) {
								console.error(e);
								this.compatibleFile = true;
							}
						} else {
							this.compatibleFile = true;
						}

					}, false);
				},
				methods: {
					toast(msg) {
						plus.nativeUI.toast(msg,{
							verticalAlign: this.prohibited.verticalAlign || 'center',
							duration: 'long'
						});
					},
					clear(name) {
						if (!name) {
							this.files.clear();
							return;
						}
						this.files.delete(name);
					},
					setData(option = '{}') {
						this.debug && console.log('更新参数：' + option);
						try {
							_this.option = JSON.parse(option);
						} catch (e) {
							console.error('参数设置错误')
						}
					},
					setFiles(files) {
						_this.files = new Map(JSON.parse(files));
					},
					async upload(name = '') {
						let arr = [];

						if (name && this.files.has(name)) {
							arr.push(this.files.get(name));
						} else {
							arr = [...this.files.values()].filter(_ => _.type === 'waiting' || _.type === 'fail');
						}

						for (let item of arr) {
							if (!this.prohibited.toBase) {
								await this.createUpload(item);
							} else {
								let _this = this;
								let reader = new FileReader();
								reader.readAsDataURL(item.file);
								reader.onload = async function() {
									await _this.createUpload(item, this.result.replace(/[\r\n]/g, ""));
								}
								reader.onerror = function() {
									throw 'file to base64 error';
								}
							}
						}
					},
					permissionModal(p) {
						let message = p.message || '是否前往开启权限？'
						plus.nativeUI.confirm(message, (e) => {
							this.closeToast(p.value);
							if (e.index === 0) {
								gotoAppPermissionSetting();
							}
						}, '提示', ['确定', '取消']);
					},
					permissionToast(p) {
						if (this.prohibited.isPermissionInToast) {
							const styles = {
								background: '#292D32',
								color: '#FFFFFF'
							};
							this.Toast[p.value] = new plus.nativeObj.View('toast', {
								top: '80px',
								left: '5%',
								height: (p.height ? p.height : '100px'),
								width: '90%',
							});
							this.Toast[p.value].drawRect({
								color: styles.background,
								radius: `10px`
							}, {
								top: '0px',
								left: '0px',
								width: '100%',
								height: '100%'
							});
							this.Toast[p.value].draw([{
									tag: 'font',
									id: 'fonttitle',
									text: p.title || '提示：',
									textStyles: {
										size: `15px`,
										color: styles.color,
										align: "left",
										whiteSpace: 'normal',
										verticalAlign: 'top',
										weight: 'bold'
									},
									position: {
										left: '15px',
										width: '92%',
										top: '15px'
									}
								},
								{
									tag: 'font',
									id: 'font',
									text: p.message,
									textStyles: {
										size: `15px`,
										color: styles.color,
										align: "left",
										whiteSpace: 'normal',
										verticalAlign: 'top'
									},
									position: {
										left: '15px',
										width: '92%',
										top: '45px'
									}
								}
							]);
							this.Toast[p.value].show();
						} else {
							location.href =
								`callback?retype=permissionBefore&permission=${p.value}&message=${encodeURIComponent(p.message)}`;
						}
					},
					closeToast(toastId) {
						if (this.Toast[toastId]) {
							this.Toast[toastId].close();
							this.Toast[toastId] = null;
						}
					},
					async onClick(event) {
						if (this.isIos) {
							let permission = this.prohibited.permission.ios;
							if (permission && permission.length) {
								let t = null;
								for (let p of permission) {
									t = setTimeout(() => {
										this.permissionToast(p);
									}, 500);
									let result = judgeIosPermission(p.value)
									if (!result) {
										this.debug && console.error('用户未同意权限，提示用户申请');
										event.preventDefault();
										location.href =
											`callback?retype=permissionFail&permission=${p.value}&permissionResult=${result}&message=${encodeURIComponent(p.message)}`;
										if (this.prohibited.isPermissionInModal) {
											this.permissionModal(p);
										}
									} else {
										clearTimeout(t)
									}

								}
							}
						} else if (!this.compatibleFile) {
							let permission = this.prohibited.permission.android;
							if (permission && permission.length) {
								let t = null;
								for (let p of permission) {
									this.closeToast(p.value);
									t = setTimeout(() => {
										this.permissionToast(p);
									}, 200)
									let _dom = null;
									let result = await requestAndroidPermission(p.value)
									this.closeToast(p.value);
									if (result !== 1) {
										event.preventDefault();
										this.debug && console.error('用户未同意权限，提示用户申请');
										location.href =
											`callback?retype=permissionFail&permission=${p.value}&permissionResult=${result}&message=${encodeURIComponent(p.message)}`;
										if (this.prohibited.isPermissionInModal) {
											this.permissionModal(p);
										}
										return;
									} else {
										clearTimeout(t)
									}
								}
								clearTimeout(t)
								setTimeout(() => {
									// for (let val of this.Toast) {
									// 	if (val) {
									// 		val.close();
									// 	}
									// }
									this.dom.click();
									this.dom.classList.add('file');
									document.getElementById('btn').appendChild(this.dom);
								}, 0)
							} else {
								setTimeout(() => {
									this.dom.click();
									this.dom.classList.add('file');
									document.getElementById('btn').appendChild(this.dom);
								}, 0)
							}
						}
					},
					async onChange(e) {
						let fileDom;
						if (!this.compatibleFile) {
							fileDom = e.target || this.dom;
						} else {
							fileDom = this.$refs.file;
						}
						for (let file of fileDom.files) {
							if (this.files.size >= this.prohibited.count) {
								this.toast(`只允许上传${this.prohibited.count}个文件`);
								fileDom.value = '';
								break;
							}
							await this.addFile(file);
						}
						this.uploadAfter();
						fileDom.value = '';
					},
					addFile(file) {
						return new Promise((resolve, reject) => {
							if (file) {
								let name = file.name;
								this.debug && console.log('文件名称', name, '大小', file.size);
								// 限制文件格式
								let suffix = name.substring(name.lastIndexOf(".") + 1).toLowerCase();
								let formats = this.prohibited.formats.toLowerCase();
								if (formats && !formats.includes(suffix)) {
									this.toast(`不支持上传${suffix.toUpperCase()}格式文件`);
									return resolve();
								}
								// 限制文件大小
								if (file.size > 1024 * 1024 * Math.abs(this.prohibited.size)) {
									this.toast(`附件大小请勿超过${this.prohibited.size}M`)
									return resolve();
								}
								try {
									if (!this.prohibited.distinct) {
										let duplicateFile = [...this.files.keys()].filter(item => {
											return (item.substring(0, item.lastIndexOf("(")) || item
													.substring(0, item.lastIndexOf("."))) == name
												.substring(0, name.lastIndexOf(".")) &&
												item.substring(item.lastIndexOf(".") + 1)
												.toLowerCase() === suffix;
										})
										if (duplicateFile.length) {
											name =
												`${name.substring(0,name.lastIndexOf("."))}(${duplicateFile.length}).${suffix}`;
										}
									}
								} catch (e) {
									name = Date.now() + '_' + name;
								}
								let path = URL.createObjectURL(file);
								this.files.set(name, {
									file,
									path,
									name: name,
									size: file.size,
									progress: 0,
									type: 'waiting'
								});
								return resolve();

							}
						})
					},
					/**
					 * @returns {Map} 已选择的文件Map集
					 */
					callChange() {
						location.href = 'callback?retype=change&files=' + encodeURIComponent(JSON.stringify([...this
							.files
						]));
					},
					/**
					 * @returns {object} 正在处理的当前对象
					 */
					changeFilesItem(item, end = '') {
						this.files.set(item.name, item);
						location.href = 'callback?retype=progress&end=' + end + '&item=' + encodeURIComponent(JSON
							.stringify(item));
					},
					uploadAfter() {
						this.callChange();
						setTimeout(() => {
							this.instantly && this.upload();
						}, 1000)
					},
					compressImg(base64, multiple, useImg) {
						// 第一个参数就是需要加密的base64，
						// 第二个是压缩系数 0-1，
						// 第三个压缩后的回调 用来获取处理后的 base64
						if (!base64) {
							return
						}
						// const _this = this
						const length = base64.length / 1024
						// 压缩方法
						let newImage = new Image()
						let quality = 0.6 // 压缩系数0-1之间
						newImage.src = base64
						newImage.setAttribute('crossOrigin', 'Anonymous') // url为外域时需要
						let imgWidth,
							imgHeight
						let w = undefined
						newImage.onload = function() {
							// 这里面的 this 指向 newImage
							// 通过改变图片宽高来实现压缩
							w = this.width * multiple
							imgWidth = this.width
							imgHeight = this.height
							let canvas = document.createElement('canvas')
							let ctx = canvas.getContext('2d')
							if (Math.max(imgWidth, imgHeight) > w) {
								if (imgWidth > imgHeight) {
									canvas.width = w
									// 等比例缩小
									canvas.height = w * (imgHeight / imgWidth)
								} else {
									canvas.height = w
									// 等比例缩小
									canvas.width = w * (imgWidth / imgHeight)
								}
							} else {
								canvas.width = imgWidth
								canvas.height = imgHeight
								// quality 设置转换为base64编码后图片的质量，取值范围为0-1  没什么压缩效果
								// 还是得通过设置 canvas 的宽高来压缩
								quality = 0.6
							}
							ctx.clearRect(0, 0, canvas.width, canvas.height)
							ctx.drawImage(this, 0, 0, canvas.width, canvas.height) //  // 这里面的 this 指向 newImage
							let smallBase64 = canvas.toDataURL('image/png', quality) // 压缩语句
							// 如想确保图片压缩到自己想要的尺寸,如要求在50-150kb之间，请加以下语句，quality初始值根据情况自定
							// while (smallBase64.length / 1024 > 150) {
							// quality -= 0.01;
							// smallBase64 = canvas.toDataURL("image/jpeg", quality);
							// }
							// 防止最后一次压缩低于最低尺寸，只要quality递减合理，无需考虑
							// while (smallBase64.length / 1024 < 50) {
							// quality += 0.001;
							// smallBase64 = canvas.toDataURL("image/jpeg", quality);
							// }

							// 必须通过回调函数返回，否则无法及时拿到该值，回调函数异步执行
							console.log(`压缩前：${length}KB`)
							console.log(`压缩后：${smallBase64.length / 1024} KB`);
							return useImg(base64);
						}
					},
					createUpload(item, base64) {
						this.debug && console.log('准备上传,option=：' + JSON.stringify(this.option));
						item.type = 'loading';
						delete item.responseText;
						return new Promise((resolve, reject) => {
							let {
								url,
								name,
								method = 'POST',
								header = {},
								formData = {}
							} = this.option;
							let form = new FormData();
							for (let keys in formData) {
								form.append(keys,decodeURI(formData[keys]))
							}
							let xmlRequest;
							if (!this.prohibited.toBase) {
								form.append(name, item.file);
								xmlRequest = new XMLHttpRequest();
								xmlRequest.upload.addEventListener(
									'progress',
									event => {
										if (event.lengthComputable) {
											let progress = Math.ceil((event.loaded * 100) / event.total)
											if (progress <= 100) {
												item.progress = progress;
												this.changeFilesItem(item);
											}
										}
									},
									false
								);
							} else {
								form.append(name, base64);
								xmlRequest = new plus.net.XMLHttpRequest();
								xmlRequest.onprogress = event => {
									if (event.lengthComputable) {
										let progress = Math.ceil((event.loaded * 100) / event.total)
										console.log('progress', progress);
										if (progress <= 100) {
											item.progress = progress;
											this.changeFilesItem(item);
										}
									}
								}
							}

							xmlRequest.open(method, url, true);
							for (let keys in header) {
								xmlRequest.setRequestHeader(keys, header[keys])
							}

							xmlRequest.ontimeout = () => {
								console.error('请求超时')
								item.type = 'fail';
								this.changeFilesItem(item, true);
								return resolve(false);
							}

							xmlRequest.onreadystatechange = ev => {
								if (xmlRequest.readyState == 4) {
									this.debug && console.log('接口是否支持跨域', xmlRequest.withCredentials);
									if (xmlRequest.status == 200) {
										this.debug && console.log('上传完成：' + xmlRequest.responseText)
										item['responseText'] = xmlRequest.responseText;
										item.type = 'success';
										this.changeFilesItem(item, true);
										return resolve(true);
									} else if (xmlRequest.status == 0) {
										console.error(
											'status = 0 :请检查请求头Content-Type与服务端是否匹配，服务端已正确开启跨域，并且nginx未拦截阻止请求'
										)
									}
									console.error('--ERROR--：status = ' + xmlRequest.status)
									item.type = 'fail';
									this.changeFilesItem(item, true);
									return resolve(false);
								}
							}

							function isContentTypeJson(header) {
								try {
									const contentType = header && header['Content-Type'];
									return contentType && contentType.includes('application/json');
								} catch (error) {
									return false
								}
							}

							if (isContentTypeJson(header)) {
								const formObject = {};
								for (let [key, value] of form.entries()) {
									formObject[key] = value;
								}
								xmlRequest.send(JSON.stringify(formObject))
							} else {
								xmlRequest.send(form)
							}
						});

					}

				}
			});
		</script>
	</body>

</html>